package com.dai.dao;

import com.dai.bean.User;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDate;

@Component("userDAO")
public class UserDAO extends BaseDAO<User> {

    final Object locker = new Object();

    public User getUserByUserId(int user_id){
        String sql = String.format("select * from user where user_id = %d;",user_id);
        User user = get(sql);
        return  user;
    }

    public void updateUserBuShu(User user){
        String sql = String.format("update user set bushu = %d,sys_bushu = %d,sync_daytime='%s' where user_id = %d; ",
                user.bushu,user.sys_bushu,user.sync_daytime,user.user_id);
        run(sql);
    }

    public void updateUserCoin(User user){
        String sql = String.format("update user set coin = %d where user_id = %d; ",
                user.coin,user.user_id);
        run(sql);
    }

    public int newUser(int sysBuShu){
        String name = "游客" + System.currentTimeMillis();
        String dayTime = LocalDate.now().toString();
        String sql = String.format("insert into user (name,sys_bushu,sync_daytime) values ('%s',%d,'%s');",
                name,
                sysBuShu,
                dayTime);
        String sqlNewInsert = "select last_insert_rowid() from user";
        int newId = -1;
        synchronized (locker){
            run(sql);
            newId = getIntId(sqlNewInsert);
        }
        return newId;
    }

    // 归档
    public void placeOn(User user){
        String sql = String.format("insert into data_bushu (user_id,bushu,daytime) values (%d,%d,'%s');",
                user.user_id,
                user.bushu,
                user.sync_daytime);
        run(sql);
    }
}
